package org.jeecg.modules.simulator.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.simulator.jsonot.ODRoutes;
import org.jeecg.modules.simulator.jsonot.RoutePath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: simulator-b20240918
 * @description: Redis解析与反解析工具
 * @author: renzhg
 * @create: 2025-01-23 13:56
 **/
public class RedisSimUtil {
  RedisTemplateHolder redisTemplateHolder;
  private final Gson gson = new Gson(); // Gson 实例
  public RedisSimUtil(){

    redisTemplateHolder =new RedisTemplateHolder();
  }


  private final String prefixRouteName = "Simu_";

  public  ODRoutes getODRoutesObject(String routeId){

    RedisTemplate redisTemplate = redisTemplateHolder.getRedisTemplate();
    String querystr=prefixRouteName+routeId;
//    System.out.println(querystr);
    if(redisTemplate.hasKey(querystr)){
      String jsonResult = oConvertUtils.getString(redisTemplate.opsForValue().get(querystr));
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      ODRoutes odRoutes = gson.fromJson(jsonResult, ODRoutes.class);
      return odRoutes;
    }
    return null;

  }


//传入站点，通过模糊查询查出所有od
  public List<ODRoutes>  getODRouteListObject(String stationId){
    String querystr=prefixRouteName+stationId+"*";

    return getObjectsByWildcard(querystr, ODRoutes.class);


  }

  /**
   * 反序列化字符串为目标对象
   *
   * @param value 字符串值
   * @param clazz 目标类
   * @param <T>   泛型类型
   * @return 反序列化后的对象
   */
  private <T> T deserialize(String value, Class<T> clazz) {
    try {
      return gson.fromJson(value, clazz); // 使用 Gson 反序列化
    } catch (JsonSyntaxException e) {
      throw new RuntimeException("反序列化失败", e);
    }
  }


  public <T> List<T> getObjectsByWildcard(String querystr, Class<T> clazz) {
    RedisTemplate redisTemplate = redisTemplateHolder.getRedisTemplate();
    // 获取所有符合查询条件的键
    Set<String> keys = redisTemplate.keys(querystr);

    if (keys == null || keys.isEmpty()) {
      return Collections.emptyList(); // 如果没有匹配的键，返回空列表
    }

    // 从 Redis 获取值并进行反序列化
    return keys.stream()
            .map(key -> redisTemplate.opsForValue().get(key))
            .filter(value -> value != null) // 过滤掉 null 值
            .map(value -> deserialize((String) value, clazz))
            .collect(Collectors.toList());
  }


  public boolean getRouteObject(String odstr, String routeIds) {
    RedisTemplate   redisTemplate =   redisTemplateHolder.getRedisTemplate();




    RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
    try {
      if (redisTemplate.hasKey(odstr)) {
        String jsonResult = oConvertUtils.getString(redisTemplate.opsForValue().get(odstr));
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        ODRoutes odRoutes = gson.fromJson(jsonResult, ODRoutes.class);
        List<RoutePath> routePathList = odRoutes.getRoutePathList();
        for (RoutePath routePath : routePathList) {
          if (routePath.getRouteName().equals(routeIds)) {
            connection.close();
            return true;

          }
        }
      }
      return false;
    }catch (Exception e){

      e.printStackTrace();
      connection.close();

    }finally {
      connection.close();
    }
    return false;
  }
}
